//
//  YMMedicalTools.m
//  YMMedical
//
//  Created by y s on 2023/7/25.
//

#import "YMMedicalTools.h"
#import "YMToolChooseDateSheet.h"
#import "YMToolChooseStatusSheet.h"

@implementation YMMedicalTools

/** 选择性别 */
+ (void)chooseSexSheet:(void(^)(NSString *sex, NSInteger index))success{
    YMToolChooseStatusSheet *vSheet = [[YMToolChooseStatusSheet alloc] init];
    vSheet.arrData = @[KLanguage(@"man_txt"),KLanguage(@"woman_txt")];
    vSheet.textSureBlock = ^(NSString * _Nonnull text, NSInteger index) {
        if (success){
            success(text,index);
        }
    };
    [vSheet show];
}
/** 选择出生日期 */
+ (void)chooseBirthDay:(void(^)(NSString *year))success{
    YMToolChooseDateSheet *vSheet = [[YMToolChooseDateSheet alloc] init];
    vSheet.dateFormat = @"yyyy-MM-dd";
    vSheet.minDate = [YMMedicalTools ddpGetExpectTimestamp:-100 month:0 day:0];
    vSheet.sureDateBlock = ^(NSString * _Nonnull dateStr) {
        if (success){
            success(dateStr);
        }
    };
    [vSheet show];
}


//获取图片第一帧
+ (UIImage *)firstFrameWithVideoURL:(NSString *)urlStr size:(CGSize)size
{
    // 获取视频第一帧
    NSURL *url = [NSURL URLWithString:urlStr];
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(size.width, size.height);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
    {
        return [UIImage imageWithCGImage:img];
    }
    return nil;
}

+ (NSMutableAttributedString *)getHtmlStringWithString:(NSString *)string{
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
                              NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)};
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    // 设置段落格式
    NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
    para.lineSpacing = [SFitUtil fit:4];
    [attStr addAttribute:NSParagraphStyleAttributeName value:para range:NSMakeRange(0, attStr.length)];
    return attStr;
}

/** 计算距离当前的有多少年  */
+ (NSString *)calculateYearToNow:(NSString *)year{
    if (year != nil && year.length > 7){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        //生日
        NSDate *birthDay = [dateFormatter dateFromString:year];
        NSCalendar *calendar = [NSCalendar currentCalendar];//定义一个NSCalendar对象
        unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
        NSDateComponents *date = [calendar components:unitFlags fromDate:birthDay toDate:[NSDate date] options:0];
        
        return [NSString stringWithFormat:@"%ld",[date year]];
    }
    return @"";
}

//获取检测报告 距离这次检测报告35天数组
+ (NSArray *)getXDateArray:(NSString *)endDate count:(NSInteger)count{
    if (endDate == nil || endDate.length < 1){
        return @[];
    }
    NSDateFormatter *matter = [[NSDateFormatter alloc] init];
    matter.dateFormat = @"yyyy-MM-dd";
    NSDate *dateNo = [matter dateFromString:endDate];
    matter.dateFormat = @"yyyy/MM/dd";
    NSString *dateNoStr = [matter stringFromDate:dateNo];
    NSString *startDate = [self getPreDataWithDate:endDate count:count];
    NSMutableArray *allXDate = [NSMutableArray arrayWithArray:[self getDatesWithStartDate:startDate endDate:dateNoStr]];
    return [allXDate copy];
}

+ (NSString *)getPreDataWithDate:(NSString *)dateNow count:(NSInteger)count{
    NSDateFormatter *matter = [[NSDateFormatter alloc] init];
    matter.dateFormat = @"yyyy/MM/dd";
    NSDate *date = [matter dateFromString:dateNow];
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60*count sinceDate:date];
    NSString *dateStr = [matter stringFromDate:lastDay];
    return dateStr;
}
+ (NSArray *)getDatesWithStartDate:(NSString *)startDate endDate:(NSString *)endDate{
     NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
     //字符串转时间
     NSDateFormatter *matter = [[NSDateFormatter alloc] init];
     matter.dateFormat = @"yyyy/MM/dd";
     NSDate *start = [matter dateFromString:startDate];
     NSDate *end = [matter dateFromString:endDate];
     NSMutableArray *componentAarray = [NSMutableArray array];
     NSComparisonResult result = [start compare:end];
     NSDateComponents *comps;
     while (result != NSOrderedDescending) {
        comps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |  NSCalendarUnitWeekday fromDate:start];
        [componentAarray addObject:start];
        //后一天
        [comps setDay:([comps day]+1)];
        start = [calendar dateFromComponents:comps];
        //对比日期大小
        result = [start compare:end];
    }
    NSMutableArray *arrDateStr = [[NSMutableArray alloc] init];
    for (NSDate *item in componentAarray) {
        NSString *dateStr = [matter stringFromDate:item];
        [arrDateStr addObject:dateStr];
    }
    return arrDateStr;
}


+ (NSDate *)ddpGetExpectTimestamp:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day {
    
    ///< 当前时间
    NSDate *currentdata = [NSDate date];
    
    ///< NSCalendar -- 日历类，它提供了大部分的日期计算接口，并且允许您在NSDate和NSDateComponents之间转换
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    /*
     ///<  NSDateComponents：时间容器，一个包含了详细的年月日时分秒的容器。
     ///< 下例：获取指定日期的年，月，日;*/
    NSDateComponents *datecomps = [[NSDateComponents alloc] init];
    [datecomps setYear:year?:0];
    [datecomps setMonth:month?:0];
    [datecomps setDay:day?:0];
    ///< dateByAddingComponents: 在参数date基础上，增加一个NSDateComponents类型的时间增量
    NSDate *calculatedate = [calendar dateByAddingComponents:datecomps toDate:currentdata options:0];
    return calculatedate;
}

+ (NSString *)sexName:(NSString *)languege{
    if ([languege isEqualToString:KLanguage(@"man_txt")]){
        return @"男";
    }else if (languege == KLanguage(@"woman_txt")){
        return @"女";
    }else{
        return languege;
    }
}
+ (NSString *)showGender:(NSString *)gender{
    if ([gender isEqualToString:@"男"]){
        return KLanguage(@"man_txt");
    }else if ([gender isEqualToString:@"女"]){
        return KLanguage(@"woman_txt");
    }else{
        return gender;
    }
}

@end
